import type { RequestConfig, RunTimeLayoutConfig } from 'umi';
import { getLocale } from 'umi';
import type { InitState } from './layouts';
import { getRunTimeLayoutConfig, getSysName, loginPath } from './layouts';
import { PageLoading } from '@ant-design/pro-layout';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import { getUserInfo, login } from '@/services/cpasRequest';
import { reqInterceptor, errorHandler } from './services';
import getRTS from './layouts/runtimeSettings';
import PageTab, { AudTabPage } from '@/components/PageTab';
import { isRunInFrame, isOpenFromJobSystem, isOpenFromPlatform } from './utils/env';

import enMessages from 'devextreme/localization/messages/en.json';
import zhMessages from 'devextreme/localization/messages/zh.json';
import { locale, loadMessages } from 'devextreme/localization';

import 'devextreme/dist/css/dx.light.css';
import '../node_modules/amis/lib/themes/cxd.css';
import '../node_modules/amis/lib/helper.css';
import '../node_modules/amis/sdk/iconfont.css';
import 'antd/dist/antd.variable.min.css';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

// window.setup = (locale) => {
//   console.log('setup');
//   // const { initialState, loading, error, refresh, setInitialState } = useModel('@@initialState');
//   // setInitialState((state) => {
//   //   return { ...state, abc: 1 };
//   // });
//   setLocale(locale, true);
// };

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<InitState> {
  devLocale();
  const rts = await getRTS();
  const fetchUserInfo = async () => {
    try {
      const loginHeader = {};
      if (isRunInFrame) {
        const { usercode, password } = history.location.query as any;
        const data = await login({ usercode, password }, loginHeader);
        if (!data.ok) return {};
      }
      if (isOpenFromJobSystem) {
        const { usercode, password } = history.location.query as any;
        const data = await login({ usercode, password }, loginHeader);
        // console.log(history.location);
        if (!data.ok) return {};
        if (history.location.pathname === '/home') {
          history.push('/home');
        }
      }
      const msg = await getUserInfo();
      if (msg.ok) {
        return msg.data;
      }
      history.push(loginPath);
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  const pathName = history.location.pathname;
  //electron平台
  if (window["electronComponents"]) {
    if (localStorage.getItem("cpasMainToken")) {
      const curUser = JSON.parse(localStorage.getItem("cpasUserInfo"))
      const sysName = getSysName(pathName);
      if (pathName === '/') history.push('/home');
      return {
        fetchUserInfo,
        settings: rts,
        curUser,
        sysName,
      };
    }
  }
  if (pathName === '/') history.push('/home');
  if (pathName !== loginPath) {
    const curUser = await fetchUserInfo();
    const cachedPassword = localStorage.getItem('password');
    if (cachedPassword) {
      curUser.password = cachedPassword;
    }
    const sysName = getSysName(pathName);
    return {
      fetchUserInfo,
      settings: rts,
      curUser,
      sysName,
    };
  }
  return {
    fetchUserInfo,
    settings: rts,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }: any) => {
  AudTabPage.getInstance().initPages(initialState?.sysName);
  const layoutConfig = getRunTimeLayoutConfig(initialState);
  // console.log(layoutConfig);
  const inFrameLayout = isRunInFrame ? { hide: true, headerHeight: 0 } : {};
  const inPlatformLayout = isOpenFromPlatform ? { hide: true, headerHeight: 0 } : {};
  return {
    ...inFrameLayout,
    ...layoutConfig,
    // siderWidth: typeof SIDER_WIDTH !== 'undefined' ? SIDER_WIDTH : 208,
    siderWidth: initialState && initialState.siderWidth === 0 ? 0 : 208,
    // siderWidth: 0,
    headerHeight: initialState && initialState.headerHeight === 0 ? 0 : 48,
    // childrenRender: initialState && initialState?.curUser ? PageTab : undefined,
    rightContentRender: () => <RightContent />,
    // footerRender: () => <Footer />,
    // links: layoutLinks(),
    menuHeaderRender: undefined,
    // 自定义 403 页面
    unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
    ...inPlatformLayout,
  };
};

// 后端数据请求配置，具体看 './services/index.ts'
export const request: RequestConfig = {
  requestInterceptors: [reqInterceptor],
  // responseInterceptors: [resInterceptor],
  errorHandler,
};

// 原 { routes } 报错，所以使用以下方法
// export function patchRoutes(Routes: any) {
//   const { routes } = Routes;
//   // 这个时候的 icon 还是string,所以应该可以在这里修改图标
//   AudTabPage.getInstance().setRoutes(routes);
// }

function devLocale() {
  // dev extreme local setting
  loadMessages(enMessages);
  loadMessages(zhMessages);
  const loca = getLocale();
  locale(loca?.slice(0, 2) || 'zh');
}
